package com.software.loginregister.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;


import com.software.loginregister.LoginActivity;
import com.software.loginregister.R;
import com.software.loginregister.api.UserHealthApi;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.UserDetail;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HealthEditActivity extends AppCompatActivity {
    private EditText editHeight, editWeight, editTaste, editAllergen, editDietaryRestrictions;
    private TextView buttonSave;
    private Long userId;
    private static final int REQUEST_TASTE_SELECTION = 1001;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health_edit);
        // 获取当前用户ID
        userId = SharedPreferencesUtil.getUserId(this);
        if (userId == -1) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, LoginActivity.class));
            finish();
            return;
        }
        initViews();

        editTaste.setOnClickListener(v -> openTasteSelection());
        // 设置输入框不可编辑，只能通过选择界面修改
        editTaste.setFocusable(false);
        editTaste.setFocusableInTouchMode(false);
        // 检查是否有从登录页面传来的饮食偏好
        String tastePreferences = SharedPreferencesUtil.getTastePreferences(this);
        if (!TextUtils.isEmpty(tastePreferences)) {
            editTaste.setText(tastePreferences);
            // 清除临时存储的饮食偏好
            SharedPreferencesUtil.clearTastePreferences(this);
        } else {
            // 如果没有新的饮食偏好，加载已保存的数据
            loadUserHealthData();
        }

        // 从网络加载数据
        loadHealthData();
        setStatusBar();
        buttonSave.setOnClickListener(v -> saveUserHealthData());
    }
    private void openTasteSelection() {
        Intent intent = new Intent(this, TasteSelectionActivity.class);
        intent.putExtra("fromHealthEdit", true);
        intent.putExtra("userId", userId);
        // 传递当前已选择的口味
        intent.putExtra("currentTaste", editTaste.getText().toString());
        startActivityForResult(intent, REQUEST_TASTE_SELECTION);
    }

    private void initViews() {
        editHeight = findViewById(R.id.editHeight);
        editWeight = findViewById(R.id.editWeight);
        editTaste = findViewById(R.id.editTaste);
        editAllergen = findViewById(R.id.editAllergen);
        editDietaryRestrictions = findViewById(R.id.editDietaryRestrictions);
        buttonSave = findViewById(R.id.btnSave);
    }

    private void loadHealthData() {
        RetrofitClient.getInstance()
                .create(UserHealthApi.class)
                .getUserHealth(userId)
                .enqueue(new Callback<Result<UserDetail>>() {
                    @Override
                    public void onResponse(Call<Result<UserDetail>> call,
                                           Response<Result<UserDetail>> response) {

                        if (response.isSuccessful() && response.body() != null
                                && response.body().getCode() == 1) {
                            UserDetail userDetail = response.body().getData();
                            if (userDetail != null) {
                                // 更新UI和本地缓存
                                updateUIWithData(userDetail);
                                saveToLocalCache(userDetail);
                            } else {
                                // 如果没有数据，尝试从本地缓存加载
                                loadFromLocalCache();
                            }
                        } else {
                            // 如果请求失败，尝试从本地缓存加载
                            loadFromLocalCache();
                        }
                    }
                    @Override
                    public void onFailure(Call<Result<UserDetail>> call, Throwable t) {
                        Log.e("HealthEdit", "Network error", t);
                        // 网络请求失败，尝试从本地缓存加载
                        loadFromLocalCache();
                    }
                });
    }

    private void loadUserHealthData() {
        // 从SharedPreferences加载数据
        SharedPreferences prefs = getSharedPreferences("user_health", MODE_PRIVATE);
        editHeight.setText(String.valueOf(prefs.getFloat("height", 0f)));
        editWeight.setText(String.valueOf(prefs.getFloat("weight", 0f)));
        editTaste.setText(prefs.getString("taste", ""));
        editAllergen.setText(prefs.getString("allergen", ""));
        editDietaryRestrictions.setText(prefs.getString("dietary_restrictions", ""));
    }

    private void saveUserHealthData() {
        // 验证输入
        if (!validateInput()) {
            return;
        }
        // 构建请求数据
        UserDetail userDetail = new UserDetail();
        userDetail.setUserId(userId);  // 设置用户ID
        userDetail.setHeight(Double.parseDouble(editHeight.getText().toString()));
        userDetail.setWeight(Double.parseDouble(editWeight.getText().toString()));
        userDetail.setTaste(editTaste.getText().toString());
        userDetail.setAllergen(editAllergen.getText().toString());
        userDetail.setDietaryRestrictions(editDietaryRestrictions.getText().toString());
        // 计算BMI
        double height = userDetail.getHeight() / 100; // 转换为米
        double weight = userDetail.getWeight();
        double bmi = weight / (height * height);
        userDetail.setBmi(bmi);
        userDetail.setBmiStatus(getBmiStatus(bmi));
        // 显示加载对话框
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("保存中...");
        progressDialog.show();
        // 发送网络请求，修改为匹配后端API
        RetrofitClient.getInstance()
                .create(UserHealthApi.class)
                .updateUserHealth(userId, userDetail)  // 修改这里，传入userId
                .enqueue(new Callback<Result<String>>() {  // 修改返回类型为String
                    @Override
                    public void onResponse(Call<Result<String>> call,
                                           Response<Result<String>> response) {
                        progressDialog.dismiss();

                        if (response.isSuccessful() && response.body() != null) {
                            Result<String> result = response.body();
                            if (result.getCode() == 1) {
                                Toast.makeText(HealthEditActivity.this,
                                        "保存成功", Toast.LENGTH_SHORT).show();

                                // 保存成功后更新本地缓存
                                saveToLocalCache(userDetail);

                                // 返回上一页
                                finish();
                            } else {
                                Toast.makeText(HealthEditActivity.this,
                                        result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(HealthEditActivity.this,
                                    "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<String>> call, Throwable t) {
                        progressDialog.dismiss();
                        Toast.makeText(HealthEditActivity.this,
                                "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private boolean validateInput() {
        if (editHeight.getText().toString().isEmpty()
                || editWeight.getText().toString().isEmpty()) {
            Toast.makeText(this, "身高和体重不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        try {
            double height = Double.parseDouble(editHeight.getText().toString());
            double weight = Double.parseDouble(editWeight.getText().toString());
            if (height <= 0 || height > 300 || weight <= 0 || weight > 500) {
                Toast.makeText(this, "请输入合理的身高体重数值", Toast.LENGTH_SHORT).show();
                return false;
            }
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private String getBmiStatus(double bmi) {
        if (bmi < 18.5) {
            return "偏瘦";
        } else if (bmi < 24) {
            return "正常";
        } else if (bmi < 28) {
            return "偏胖";
        } else {
            return "肥胖";
        }
    }

    private void saveToLocalCache(UserDetail userDetail) {
        SharedPreferences prefs = getSharedPreferences("user_health", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        if (userDetail.getHeight() != null) {
            editor.putFloat("height", userDetail.getHeight().floatValue());
        }
        if (userDetail.getWeight() != null) {
            editor.putFloat("weight", userDetail.getWeight().floatValue());
        }
        if (userDetail.getBmi() != null) {
            editor.putFloat("bmi", userDetail.getBmi().floatValue());
        }
        if (userDetail.getBmiStatus() != null) {
            editor.putString("bmi_status", userDetail.getBmiStatus());
        }
        if (userDetail.getTaste() != null) {
            editor.putString("taste", userDetail.getTaste());
        }
        if (userDetail.getAllergen() != null) {
            editor.putString("allergen", userDetail.getAllergen());
        }
        if (userDetail.getDietaryRestrictions() != null) {
            editor.putString("dietary_restrictions", userDetail.getDietaryRestrictions());
        }
        editor.apply();
    }

    private void setStatusBar() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);
        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_TASTE_SELECTION && resultCode == RESULT_OK) {
            // 重新加载口味数据
            String tastePreferences = SharedPreferencesUtil.getTastePreferences(this);
            if (!TextUtils.isEmpty(tastePreferences)) {
                editTaste.setText(tastePreferences);
            }
        }
    }
    private void loadFromLocalCache() {
        SharedPreferences prefs = getSharedPreferences("user_health", MODE_PRIVATE);

        // 获取口味偏好
        String taste = prefs.getString("taste", "");
        if (!TextUtils.isEmpty(taste)) {
            editTaste.setText(taste);
        }
        // 获取身高体重
        float height = prefs.getFloat("height", 0f);
        float weight = prefs.getFloat("weight", 0f);
        if (height > 0) {
            editHeight.setText(String.valueOf(height));
        }
        if (weight > 0) {
            editWeight.setText(String.valueOf(weight));
        }
        // 获取过敏原和饮食禁忌
        String allergen = prefs.getString("allergen", "");
        String dietaryRestrictions = prefs.getString("dietary_restrictions", "");
        if (!TextUtils.isEmpty(allergen)) {
            editAllergen.setText(allergen);
        }
        if (!TextUtils.isEmpty(dietaryRestrictions)) {
            editDietaryRestrictions.setText(dietaryRestrictions);
        }
    }
    private void updateUIWithData(UserDetail userDetail) {
        // 更新口味偏好
        if (!TextUtils.isEmpty(userDetail.getTaste())) {
            editTaste.setText(userDetail.getTaste());
        }
        // 更新身高体重
        if (userDetail.getHeight() != null && userDetail.getHeight() > 0) {
            editHeight.setText(String.format(Locale.getDefault(), "%.1f", userDetail.getHeight()));
        }
        if (userDetail.getWeight() != null && userDetail.getWeight() > 0) {
            editWeight.setText(String.format(Locale.getDefault(), "%.1f", userDetail.getWeight()));
        }
        // 更新过敏原和饮食禁忌
        if (!TextUtils.isEmpty(userDetail.getAllergen())) {
            editAllergen.setText(userDetail.getAllergen());
        }
        if (!TextUtils.isEmpty(userDetail.getDietaryRestrictions())) {
            editDietaryRestrictions.setText(userDetail.getDietaryRestrictions());
        }
    }
}